# -*- coding: utf-8 -*-
"""
Created on Fri Feb 06 09:51:52 2015

@author: 4126777
"""

import threading
import logging
import random
import time
from datetime import datetime

class DummyConnection(object):
    
    def __init__(self, port=0): 
        self.callback            = None   
        self.registeredcallbacks = {}     
        self.stop                = False
        self.running             = False
        self.registeredIDs       = []       
               
    def register(self, callback, ctype):   
        logging.getLogger().debug("Registering callback with dummy connection")          
        self.registeredcallbacks[ctype] = callback
        
    def connect(self):
        logging.getLogger().debug("Connecting to dummy")     
        return True
    
    @classmethod
    def create(cls, clientId=1):
        logging.getLogger().debug("Creating dummy")     
        return cls()
    
    def produceDummyPrices(self):
        while self.stop == False:
            self.running = True             
            for t in self.registeredcallbacks.keys():
                msg = None
                for id in self.registeredIDs: 
                    if   t == message.TickPrice:           
                        msg = makeTick(id, random.randint(0, 10))                        
                    elif t == message.UpdateMktDepth:                
                        msg = makeMktDepthTick(id, random.random(), random.randint(0, 10), random.randint(0, 1))
                    
                    logging.getLogger().debug("Sending dummy data %s" % msg)                    
                    self.registeredcallbacks[t](msg)
                
            time.sleep(0.1)  
        

    def reqMktData(self, id, contract, id2, flag): 
        if not self.running:
            self.registeredIDs.append(id)       
            logging.getLogger().debug("Requesting dummy market data")
            threading.Timer(0, self.produceDummyPrices).start()
                              
    def reqMktDepth(self, id, contract, id2):        
        if not self.running:               
            logging.getLogger().debug("Requesting dummy market data")          
            threading.Timer(0, self.produceDummyPrices).start()
        
    def cancelMktData(self, id):
        logging.getLogger().debug("Cancelling dummy market data") 
        self.stop = True
        self.running = False

    def cancelMktDepth(self, id):
        logging.getLogger().debug("Cancelling dummy market data") 
        self.stop = True
        self.running = False
        
    def placeOrder(self, orderid, contract, order):
        pass
        
    def setServerLogLevel(self, loglevel):
        pass
    
    def reqNewsBulletins(self, flag):
        pass
    
    def serverVersion(self):
        return "Dummy 1.0"
        
    def isConnected(self):
        return True    
            
    def cancelNewsBulletins(self):
        pass
    
    def disconnect(self):
        pass
        
    def disconnect(self):
        pass
        

class Message(object):

    TickSize       = 0
    TickPrice      = 1    
    UpdateMktDepth = 2
    
    
    def __init__(self):
        self.price     = 0
        self.tickerId  = 0
        self.side      = 0
        self.price     = 0
        self.size      = 0
        self.position  = 0
        self.operation = 0
        self.rectime   = datetime.utcnow()
        self.type      = None  #only for use in DummyConnection class - not an Ibmessage field
        
    def __repr__(self, *args, **kwargs):
        return "type %s, price %s" % (self.type, self.price)
    
def makeTick(id, price):
    msg = Message()
    msg.tickerId = id
    msg.price    = price
    msg.type     = "Tick"
    return msg

def makeMktDepthTick(id, price, size, side):
    msg = Message()
    msg.tickerId = id
    msg.price    = price
    msg.size     = size
    msg.side     = side
    msg.type     = "MarketDepth"
    return msg


Connection = DummyConnection
ibConnection = DummyConnection
message = Message()